package com.xingkong.explorer2;


import android.content.Context;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class NewsTitleFragment extends Fragment implements AdapterView.OnItemClickListener{

    private ListView newsTitleListView;
    private List<News> newsList;
    private NewsAdapter adpater;
    private boolean isTwoPane;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        newsList=getNews();
        adpater=new NewsAdapter(getActivity(),R.layout.news_item,newsList);
        Log.d("test","onCreate");
    }

    @Override
    public void onAttach(Context context) {
        Log.d("test","attach");
        super.onAttach(context);
        newsList=getNews();
        adpater=new NewsAdapter(context,R.layout.news_item,newsList);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d("test", "test2");
        View view=inflater.inflate(R.layout.news_title_frag,container,false);
        newsTitleListView= (ListView) view.findViewById(R.id.news_title_list_view);
        newsTitleListView.setAdapter(adpater);
        newsTitleListView.setOnItemClickListener(this);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if(getActivity().findViewById(R.id.news_content_layout)!=null){
            isTwoPane=true;
        }else {
            isTwoPane=false;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        News news=newsList.get(i);
        if(isTwoPane){
            NewsContentFragment newsContentFragment= (NewsContentFragment) getFragmentManager().findFragmentById(R.id.news_content_fragment);
            newsContentFragment.refresh(news.getTitle(),news.getContent());
        }else{
            NewsContentActivity.actionStart(getActivity(),news.getTitle(),news.getContent());
        }
    }
    private List<News> getNews(){
        List<News> newsList=new ArrayList<News>();
        News news1=new News();
        news1.setTitle("Hello world,111");
        news1.setContent("a;lfkjasdkfjaflk;jkfsgjal;ksdfjakd;slfja;dflj;adfjads;lkfjklgjdakl;");
        newsList.add(news1);
        News news2=new News();
        news2.setTitle("Hello world,222");
        news2.setContent("fffffffffffffdasfljlkj;;k;jlkjkfjkdjfkjdafkj");
        newsList.add(news2);
        return newsList;
    }
}
